/**
 * 手机号登录模态框组件
 * 实现手机号验证码登录功能，包含：
 * - 手机号输入和验证
 * - 验证码发送和倒计时
 * - 验证码展示弹框
 * - 登录表单提交
 */

import { useState } from "react";
import {
  CloseOutlined,
  LeftOutlined,
  TabletOutlined,
  SafetyCertificateOutlined,
  CopyOutlined,
} from "@ant-design/icons";
import { Form, Input, Button, message, Modal } from "antd";
import styles from "./PhoneLoginModal.module.css";
import logo from "./images/login_logo.png";
import { sendVerificationCode, loginWithPhone } from "../../../../api/auth";
import { useUserStore } from "../../../../store/userStore";

/**
 * 组件属性类型定义
 * @property visible - 控制模态框显示/隐藏
 * @property onClose - 关闭模态框的回调函数
 * @property onBack - 返回上一步的回调函数
 */
type PhoneLoginModalProps = {
  visible: boolean;
  onClose: () => void;
  onBack: () => void;
};

export default function PhoneLoginModal({
  visible,
  onClose,
  onBack,
}: PhoneLoginModalProps) {
  // 表单实例
  const [form] = Form.useForm();
  
  // 状态管理
  const [countdown, setCountdown] = useState(0);  // 验证码倒计时
  const [loading, setLoading] = useState(false);  // 加载状态
  const [phoneValid, setPhoneValid] = useState(false);  // 手机号验证状态
  
  // 验证码弹框状态
  const [captchaModal, setCaptchaModal] = useState<{
    visible: boolean;
    code: string;
  }>({
    visible: false,
    code: "",
  });
  
  // 从用户状态管理中获取更新方法
  const { setTokens, setUserInfo } = useUserStore();

  if (!visible) return null;

  /**
   * 复制验证码到剪贴板
   * 复制成功后自动关闭验证码弹框
   */
  const handleCopyCode = async () => {
    try {
      await navigator.clipboard.writeText(captchaModal.code);
      message.success("验证码已复制到剪贴板");
      setCaptchaModal({ visible: false, code: "" });
    } catch (err) {
      message.error("复制失败，请手动复制");
    }
  };

  /**
   * 验证手机号格式
   * 更新手机号验证状态，用于控制发送验证码按钮的启用/禁用
   */
  const validatePhone = async () => {
    try {
      await form.validateFields(["phone"]);
      setPhoneValid(true);
    } catch (error) {
      setPhoneValid(false);
    }
  };

  /**
   * 发送验证码
   * 1. 验证手机号
   * 2. 调用发送验证码API
   * 3. 开始倒计时
   * 4. 显示验证码弹框
   */
  const handleSendCode = async () => {
    try {
      const { phone } = await form.validateFields(["phone"]);
      setLoading(true);
      const response = await sendVerificationCode(phone);
      
      // 开始60秒倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      // 显示验证码弹框
      setCaptchaModal({
        visible: true,
        code: response.data.captcha.toString(),
      });

      message.success(response.message);
    } catch (error: any) {
      if (error.errorFields) {
        message.error("请输入正确的手机号");
      } else {
        message.error(error.message || "发送验证码失败");
      }
    } finally {
      setLoading(false);
    }
  };

  /**
   * 处理登录提交
   * 1. 验证表单数据
   * 2. 调用登录API
   * 3. 保存用户token和信息
   * 4. 关闭登录弹框
   */
  const handleLogin = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const response = await loginWithPhone(
        values.phone,
        values.verificationCode
      );

      // 保存登录信息到全局状态
      setTokens(response.data.accessToken, response.data.refreshToken);
      setUserInfo({ phone: values.phone });

      message.success(response.message);
      onClose();
    } catch (error: any) {
      if (error.errorFields) {
        message.error("请填写完整的登录信息");
      } else {
        message.error("登录失败");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <div className={styles.modalMask} onClick={onClose}>
        <div
          className={styles.modalContent}
          onClick={(e) => e.stopPropagation()}
        >
          <div className={styles.modalHeader}>
            <LeftOutlined className={styles.backIcon} onClick={onBack} />
            <img src={logo} alt="logo" className={styles.logo} />
            <CloseOutlined className={styles.closeIcon} onClick={onClose} />
          </div>
          <div className={styles.mainContent}>
            <h3 className={styles.title}>手机号登录</h3>
            <Form form={form} layout="vertical" autoComplete="off">
              <Form.Item
                name="phone"
                rules={[
                  { required: true, message: "请输入手机号" },
                  { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
                ]}
              >
                <Input
                  placeholder="请输入手机号"
                  className={styles.input}
                  prefix={<TabletOutlined />}
                  onChange={validatePhone}
                />
              </Form.Item>
              <Form.Item
                name="verificationCode"
                rules={[
                  { required: true, message: "请输入验证码" },
                  { len: 6, message: "验证码必须是6位数字" },
                ]}
              >
                <div className={styles.verificationCodeGroup}>
                  <Input
                    placeholder="请输入验证码"
                    className={styles.input}
                    prefix={<SafetyCertificateOutlined />}
                  />
                  <Button
                    className={styles.sendCodeBtn}
                    onClick={handleSendCode}
                    disabled={!phoneValid || countdown > 0 || loading}
                  >
                    {countdown > 0 ? `${countdown}s后重新发送` : "获取验证码"}
                  </Button>
                </div>
              </Form.Item>
              <Button
                type="primary"
                className={styles.loginButton}
                onClick={handleLogin}
                loading={loading}
                disabled={!phoneValid}
              >
                登录
              </Button>
            </Form>
            <div className={styles.agreement}>
              注册或点击登录代表您同意
              <a href="#" className={styles.link}>
                《包图网络服务使用协议》
              </a>
              &amp;
              <a href="#" className={styles.link}>
                《包图隐私政策》
              </a>
            </div>
          </div>
        </div>
      </div>

      {/* 验证码弹框 */}
      <Modal
        title="验证码"
        open={captchaModal.visible}
        onCancel={() => setCaptchaModal({ visible: false, code: "" })}
        footer={[
          <Button
            key="copy"
            type="primary"
            onClick={handleCopyCode}
            icon={<CopyOutlined />}
          >
            复制验证码
          </Button>,
          <Button
            key="close"
            onClick={() => setCaptchaModal({ visible: false, code: "" })}
          >
            关闭
          </Button>,
        ]}
      >
        <div className={styles.captchaCode}>
          您的验证码是：
          <span className={styles.codeText}>{captchaModal.code}</span>
        </div>
      </Modal>
    </>
  );
}
